import Koa from "koa";
import axios from "axios";
import { koaBody } from "koa-body";
import Router from "koa-router";
import fs from "fs";

const app = new Koa();
const router = new Router();

//curl --location 'https://fastgpt.run/api/openapi/chat/chat' \
//--header 'apikey: 64634a5355dwdw0010f77378f16d-d2w2x6jz6pn4kdpzbcd7a' \
//--header 'Content-Type: application/json' \
//--data '{
//    "chatId": "",
//    "modelId": "64634a53550010f77378f176",
//    "isStream": false,
//    "prompts": [
//        {
//            "obj": "System",
//            "value": "下面是 AI 和 Human 的对话，讨论 laf 的内容。"
//        },
//        {
//            "obj": "Human",
//            "value": "什么是 laf"
//        },
//        {
//            "obj": "AI",
//            "value": "laf 是云开发平台...."
//        },
//        {
//            "obj": "Human",
//            "value": "laf 可以做什么?"
//        }
//    ]
//}'
let convs = {};

router.get("/reload", async (ctx) => {
  convs = {};
  if (fs.existsSync("./config.csv")) {
    let config = fs.readFileSync("./config.csv").toString();
    config.split("\n").map((line) => {
      let s = line.split(",");
      convs[s[0]] = s[1];
    });
  }
  ctx.body = convs;
});

router.post("/chat", async (ctx) => {
  const {
    key,
    content,
    prefix,
    conversation_id,
    conversations,
    temperature,
  } = ctx.request.body;
  const prompt = (role, content) => {
    return {
      obj: role,
      value: content,
    };
  };
  if (convs[conversation_id]) {
    let prompts = conversations || [];
    if (prompts.length > 0) {
      prompts.map((item) => {
        return {
          obj: item.role,
          value: item.content,
        };
      });
    }
    prefix && prompts.push(prompt("System", prefix));
    let { data } = await axios({
      url: "https://fastgpt.run/api/openapi/chat/chat",
      headers: {
        apikey: key,
        "Content-Type": "application/json",
      },
      data: {
        chatId: conversation_id,
        modelId: convs[conversation_id],
        isStream: false,
        prompts: prompts,
      },
    });
    console.log(data);
    ctx.body = data;
  } else {
    let { data } = await axios.post(
      "https://gpt.deno.minapp.xin/api/chat",
      ctx.request.body
    );

    ctx.body = data;
  }
});

router.get("/", (ctx) => (ctx.body = "service start"));

app.use(koaBody());
app.use(router.routes());
app.on("error", (err) => {
  console.error(err);
});
app.listen(23061, (err) => {
  err && console.log(err);

  console.log("proxy started");
});
